package usr;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import page.PageState;



public class UsrCreate extends HttpServlet {

	public static void main(String[] args) {
		String string = "Bo@dcom";
		int i = string.indexOf('@');
		System.out.println(string.indexOf('@'));
		int j = string.indexOf('.', i);
		System.out.println(j + " " + i);
		System.out.println(j - i);
		System.out.println((j < 0 || i < 0 || j - i < 2));
	}
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		Usr usr = new Usr();
		usr.setEmail(req.getParameter("user[email]"));
		usr.setLogin(req.getParameter("user[login]"));
		usr.setPassword(req.getParameter("user[password]"));
		
		if ( usr.getPassword().length() < 6 ) {
			req.setAttribute("error_cause", PageState.PASSWORD_TOO_SHORT);
			req.getRequestDispatcher("join.jsp").forward(req, resp);
			
		} else if ( !usr.getPassword().equals(
				req.getParameter("user[password_confirmation]")) ) {
			req.setAttribute("error_cause", PageState.PASSWORD_NOT_CONSIST);
			req.getRequestDispatcher("join.jsp").forward(req, resp);
		
		} else {
			int i = usr.getEmail().indexOf('@');
			int j = usr.getEmail().indexOf('.', i);
			
			if ( i < 0 || j < 0 || j - i < 2 ) {
				req.setAttribute("error_cause", PageState.NOT_AN_EMAIL);
				req.getRequestDispatcher("join.jsp").forward(req, resp);
				
			} else {
				i = usr.create();
				if ( i != PageState.SUCCESSFUL ) {
					req.setAttribute("error_cause", i);
					req.getRequestDispatcher("join.jsp").forward(req, resp);
					return;
					
				} else {
					HttpSession session = req.getSession();
					session.setAttribute("usr", usr);
					resp.sendRedirect("dashboard.jsp"); // dashboard.jsp
				}
			}
		}
		
	}
}
